package com.gomyb.utils;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

public class RequestUtil {

    /**
     * 把浏览器参数转化放到Map集合中
     */
    public static Map<String, String> getParam(HttpServletRequest request) {
        Map<String, String> paramMap = new HashMap<>();
        String method = request.getMethod();
        Enumeration<?> keys = request.getParameterNames();
        while (keys.hasMoreElements()) {
            Object key = keys.nextElement();
            if (key != null) {
                if (key instanceof String) {
                    String value = request.getParameter(key.toString());
                    if ("GET".equals(method)) {
                        //前台encodeURIComponent('我们');转码后到后台还是ISO-8859-1，所以还需要转码
                        value = new String(value.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
                    }
                    paramMap.put(key.toString(), value);
                }
            }
        }
        return paramMap;
    }
}
